package com.im.config;

import io.minio.*;
import io.minio.errors.*;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Configuration
public class MinioConfig {

    @Value("${minio.host}")
    private String IP;
    @Value("${minio.bucketName}")
    private String BUCKET_NAME;
    @Value("${minio.accessKey}")
    private String ACCESS_KEY;
    @Value("${minio.secretKey}")
    private String SECRET_KEY;

    /**
     * 创建Minio客户端
     * 如果桶不存在，则按照只读策略创建桶
     */
    public MinioClient create() throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
        //创建一个MinIO的Java客户端
        MinioClient minioClient = MinioClient.builder().
                endpoint(IP).
                credentials(ACCESS_KEY, SECRET_KEY)
                .build();

        // 桶不存在则创建桶
        boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(BUCKET_NAME).build());
        if (!isExist) {
            // 创建桶
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(BUCKET_NAME).build());

            // 只读
            String read_only = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\"],\"Resource\":[\"arn:aws:s3:::ims\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:ListBucket\"],\"Resource\":[\"arn:aws:s3:::ims\"],\"Condition\":{\"StringEquals\":{\"s3:prefix\":[\"*\"]}}},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::ims/**\"]}]}";
            // 只写
            String write_only = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::ims\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:PutObject\",\"s3:AbortMultipartUpload\",\"s3:DeleteObject\",\"s3:ListMultipartUploadParts\"],\"Resource\":[\"arn:aws:s3:::ims/**\"]}]}";
            // 读写
            String read_write = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::ims\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:ListBucket\"],\"Resource\":[\"arn:aws:s3:::ims\"],\"Condition\":{\"StringEquals\":{\"s3:prefix\":[\"*\"]}}},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:AbortMultipartUpload\",\"s3:DeleteObject\",\"s3:GetObject\",\"s3:ListMultipartUploadParts\",\"s3:PutObject\"],\"Resource\":[\"arn:aws:s3:::ims/**\"]}]}";
            // 设置配置策略模式，可以通过URL访问文件
            SetBucketPolicyArgs setBucketPolicyArgs = SetBucketPolicyArgs.builder()
                    .bucket(BUCKET_NAME)
                    .config(read_only)
                    .build();
            minioClient.setBucketPolicy(setBucketPolicyArgs);
        }

        return minioClient;
    }

    /**
     * 压缩图片
     * 如果文件夹tmp不存在，创建文件夹
     *
     * @return
     */
    public InputStream image_small(MultipartFile file, String newFileName, String format) throws IOException {
        // 存放出压缩后的文件
        InputStream newMultipartFile = null;

        // 图片缓存文件夹
        String img_tmp = ".\\tmp\\";

        // 如果图片缓存文件夹不存在，则创建文件夹
        File create_folder = new File(img_tmp);
        if (!create_folder.isDirectory()) {
            create_folder.mkdirs();
        }

        // 压缩图片, 并且存入本地项目相对目录
        // scale:Thumbnails,范围:0.0f~1.0f
        // outputQuality:输出的图片质量,范围:0.0f~1.0f
        Thumbnails.of(file.getInputStream()).scale(0.5f).outputQuality(0.15f).outputFormat(format).toFile(img_tmp + newFileName);

        // 读取出压缩后的文件
        newMultipartFile = new FileInputStream(img_tmp + newFileName + "." + format);

        return newMultipartFile;
    }

    public String putObject(MinioClient minioClient, String newFileName, String fileType, InputStream stream, long size) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
        // 使用putObject把文件存储到桶中
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(BUCKET_NAME)
                        .object(newFileName)
                        .contentType(fileType) //定义文件上传类型
                        .stream(stream, size, -1)
                        .build()
        );
        return IP + "/" + BUCKET_NAME + "/" + newFileName;
    }
}
